package org.jeecg.modules.demo.partner.controller;


import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.base.service.BaseCommonService;
import org.jeecg.modules.demo.partner.entity.Partner;
import org.jeecg.modules.demo.partner.entity.SysUser;
import org.jeecg.modules.demo.partner.service.IPartnerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 合作商
 */
@Api(tags="Partner")
@RestController
@RequestMapping("/Partner/Partner")
@Slf4j
public class PartnerController extends JeecgController<Partner, IPartnerService> {

    @Autowired
    private IPartnerService partnerService;

    @Autowired
    private BaseCommonService baseCommonService;



    /**
     * 分页列表查询 未审核
     *
     * @param partner
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "partner-分页列表查询 未审核")
    @ApiOperation(value="partner-分页列表查询 未审核", notes="partner-分页列表查询 未审核")
    @GetMapping(value = "/list")
    public Result<IPage<Partner>> queryPageList(Partner partner,
                                                  @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                  @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                  HttpServletRequest req) {


        QueryWrapper<Partner> queryWrapper = QueryGenerator.initQueryWrapper(partner, req.getParameterMap());
        Page<Partner> page = new Page<Partner>(pageNo, pageSize);
        IPage<Partner> pageList = partnerService.page(page, queryWrapper);

        return Result.OK(pageList);
    }




    @AutoLog(value = "partner-根据合作商类型查询-不分页")
    @ApiOperation(value="partner-根据合作商类型查询-不分页", notes="partner-根据合作商类型查询-不分页")
    @PostMapping("/getPartnerByType")
    public Result<List<Partner>> getPartnerByType(@RequestBody Partner partner){

        List<Partner> partnerList = partnerService.getPartnerByType(partner.getCooperatorType());
        return Result.OK(partnerList);
    }





    @AutoLog(value = "partner-检查用户是否存在")
    @ApiOperation(value="partner-检查用户是否存在", notes="partner-检查用户是否存在")
    @PostMapping("/checkUserExists")
    public Result<String> checkUserExists(@RequestBody String json){

        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(json);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        String username = jsonObject.get("username").getAsString();

        if(partnerService.checkUserExists(username)){
            return Result.OK("用户名已存在","1");
        } else {
            return Result.OK("用户名不存在","0");
        }

    }

    @AutoLog(value = "partner-检查企业名称是否存在")
    @ApiOperation(value="partner-检查企业名称是否存在", notes="partner-检查企业名称是否存在")
    @PostMapping("/checkCompanyExists")
    public Result<String> checkCompanyExists(@RequestBody String json){

        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(json);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        String companyName = jsonObject.get("companyName").getAsString();

        if(partnerService.checkCompanyExists(companyName)){

            return Result.OK("企业名称已存在","1");
        } else {
            return Result.OK("企业名称不存在","0");
        }

    }


    /**
     *   添加
     *
     * @param partner
     * @return
     */
    @AutoLog(value = "partner-添加")
    @ApiOperation(value="partner-添加", notes="partner-添加")
    //@RequiresPermissions("partner:partner:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Partner partner) {
        if(containsChinese(partner.getUsername())){
            return Result.error("用户账号不能是中文！");
        }

        String id = String.valueOf(IdWorker.getId());
        partner.setId(id);
        partner.setUserid(id);

//        partner.setCreateTime(new Date());
        //密码加密
        String salt = oConvertUtils.randomGen(8);
        partner.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(partner.getUsername(), partner.getPassword(), salt);
        partner.setPassword(passwordEncode);


        partnerService.save(partner);
        return Result.OK("添加成功！");
    }


    /**
     *   修改
     * @param partner
     * @return
     */
    @AutoLog(value = "partner-修改")
    @ApiOperation(value="partner-修改", notes="partner-修改")
    //@RequiresPermissions("partner:partner:edit")
    @PostMapping(value = "/edit")
    public Result<String> edit(@RequestBody Partner partner) {

        if(containsChinese(partner.getUsername())){
            return Result.error("用户账号不能是中文！");
        }

        partnerService.updateById(partner);

        return Result.OK("修改成功！");
    }


    /**
     *   通过id删除
     *
     * @param json
     * @return
     */
    @AutoLog(value = "spc_flow_report-通过id删除")
    @ApiOperation(value="spc_flow_report-通过id删除", notes="spc_flow_report-通过id删除")
    //@RequiresPermissions("spcFlowReport:spc_flow_report:delete")
    @PostMapping(value = "/delete")
    public Result<String> delete(@RequestBody String json) {

        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(json);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        String id = jsonObject.get("id").getAsString();

        partnerService.removeById(id);
        return Result.OK("删除成功!");
    }



    /**
     * 检测输入的字符串是否包含中文
     * @param input
     * @return
     */
    public static boolean containsChinese(String input) {
        String regex = "[\u4e00-\u9fa5]"; // Unicode 范围：基本汉字
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(input);
        return matcher.find();
    }


    @AutoLog(value = "partner-审核")
    @ApiOperation(value="partner-审核", notes="partner-审核")
    @PostMapping("/review")
    public Result<String> review(@RequestBody String json){

        JsonParser jsonParser = new JsonParser();
        JsonElement jsonElement = jsonParser.parse(json);
        JsonObject jsonObject = jsonElement.getAsJsonObject();

        String id = jsonObject.get("id").getAsString();


        Partner partner = partnerService.getPartnerById(id);

        SysUser user = new SysUser();
        user.setId(partner.getId());
        user.setUsername(partner.getUsername());
        user.setPassword(partner.getPassword());
        user.setSalt(partner.getSalt());
        user.setRealname(partner.getCompanyName());

        user.setCreateTime(new Date());//设置创建时间
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);
        //用户表字段org_code不能在这里设置他的值
        user.setOrgCode(null);

        String cooperatorType = partner.getCooperatorType();
        String[] types = cooperatorType.split(",");


        partnerService.saveUser(user,types);

//        //获取租户ids
//        String relTenantIds = jsonObject.getString("relTenantIds");
//        // 保存用户走一个service 保证事务
//        sysUserService.saveUser(user, selectedRoles, selectedDeparts, relTenantIds);
        baseCommonService.addLog("审核合作商： " +user.getUsername() ,CommonConstant.LOG_TYPE_2, 2);

        return Result.OK("审核成功！");
    }


}
